package com.rnkrsoft.suyan.config.server.web.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rnkrsoft.reflection4j.extension.ExtensionLoader;
import com.rnkrsoft.suyan.config.server.ajax.authority.AuthorityAuthenticator;
import com.rnkrsoft.suyan.config.server.ajax.authority.AuthorityContext;
import com.rnkrsoft.suyan.config.server.ajax.authority.AuthorityExtractor;
import com.rnkrsoft.suyan.config.server.ajax.config.AjaxConfig;
import com.rnkrsoft.suyan.config.server.ajax.data.CheckAuthorityRequest;
import com.rnkrsoft.suyan.config.server.ajax.data.CheckAuthorityResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class AuthorityController {
    @Autowired
    AjaxConfig ajaxConfig;
    static Gson GSON = new GsonBuilder().serializeNulls().create();

    @RequestMapping(value = "/checkAuthority.do", method = {RequestMethod.POST})
    @ResponseBody
    public String checkAuthority(@RequestBody String json,
                               HttpServletRequest request,
                               HttpServletResponse response){
        CheckAuthorityRequest checkAuthorityRequest = GSON.fromJson(json, CheckAuthorityRequest.class);
        AuthorityExtractor authorityExtractor = ExtensionLoader.getExtensionLoader(AuthorityExtractor.class).getExtension(ajaxConfig.getAuthorityExtractorName());
        AuthorityAuthenticator authorityAuthenticator = ExtensionLoader.getExtensionLoader(AuthorityAuthenticator.class).getExtension(ajaxConfig.getAuthorityAuthenticatorName());
        AuthorityContext authorityContext = authorityExtractor.extract(request, response);
        authorityContext.setProduct(checkAuthorityRequest.getProduct());
        authorityContext.setAction(checkAuthorityRequest.getAction());
        authorityContext.setVersion(checkAuthorityRequest.getVersion());
        authorityContext.setOperate(checkAuthorityRequest.getOperate());
        boolean authority = authorityAuthenticator.hasAuthority(authorityContext);
        CheckAuthorityResponse checkAuthorityResponse = CheckAuthorityResponse.builder()
                .product(checkAuthorityRequest.getProduct())
                .action(checkAuthorityRequest.getAction())
                .version(checkAuthorityRequest.getVersion())
                .operate(checkAuthorityRequest.getOperate())
                .authority(authority)
                .build();

        return GSON.toJson(checkAuthorityResponse);
    }
}
